package stdio.costa.imoca.api;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import stdio.costa.imoca.dto.PostcardBackListDTO;
import stdio.costa.imoca.model.Activity;
import stdio.costa.imoca.model.PostcardBack;
import stdio.costa.imoca.spi.ActivitySpi;
import stdio.costa.imoca.spi.PostcardBackSpi;

import com.sun.jersey.multipart.BodyPartEntity;
import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataParam;

@Path("/postcard_back")
@Component
@Scope("request")
public class PostcardBackApi extends BaseApi {

	@Autowired
	private PostcardBackSpi postcardBackSpi;

	@Autowired
	private ActivitySpi activitySpi;

	// @Autowired
	// @Qualifier("cloudStorageProxy")
	// private StorageSpi storageSpi;

	@POST
	@Path("create")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Produces({ "application/json;qs=1", "application/xml;qs=.5" })
	public PostcardBack create(@FormDataParam("name") String name,
			@FormDataParam("description") String description,
			@FormDataParam("postcard") FormDataBodyPart bodyPart,
			@FormDataParam("designerToken") String designerToken,
			@FormDataParam("tags") String tags,
			@FormDataParam("activityUuid") String activityUuid)
			throws Exception {

		Activity activity = activitySpi.findActivityByUuid(activityUuid);

		if (activity == null) {
			throw new IllegalArgumentException("Activity does not exist.");
		}

		// FIXME add designer
		PostcardBack PostcardBack = postcardBackSpi.save(new PostcardBack(name,
				description, tags, activity));
		// upload to cloud is async, so read it from client first, don't let
		// client to wait cloud
		BodyPartEntity entity = (BodyPartEntity) bodyPart.getEntity();
		// byte[] file = IOUtils.readFully(entity.getInputStream());
		// storageSpi.uploadAsynchronously(new ByteArrayInputStream(file),
		// bodyPart.getMediaType().toString(), PostcardBack.getUuid());
		return PostcardBack;
	}

	@GET
	@Path("/{uuid}")
	@Produces({ "application/json;qs=1", "application/xml;qs=.5" })
	public PostcardBack get(@PathParam("uuid") String uuid) {
		return postcardBackSpi.findByUuid(uuid);
	}

	@GET
	@Path("/search_by_tags")
	@Produces({ "application/json;qs=1", "application/xml;qs=.5" })
	public PostcardBackListDTO searchByTags( @DefaultValue("") @QueryParam("search_words") String searchWords,
			@QueryParam("accessToken") String accessToken) {
		
		PostcardBackListDTO dto = new PostcardBackListDTO();
		
		dto.setPostcardBacks(this.postcardBackSpi.findByTags(searchWords));
		
		return dto;
	}
}
